package com.loyi.cloud.hbsystem.datashare.web;

import java.util.Date;

import javax.management.Query;

import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.loyi.cloud.hbmis.api.IQueryService;
import com.loyi.cloud.hbsystem.datashare.service.GISAnalyserExportTask;

@RestController
public class GisDataExportService {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	ThreadPoolTaskExecutor executor;

	public GisDataExportService() {
		executor = new ThreadPoolTaskExecutor();
		executor.setCorePoolSize(10);
		executor.setMaxPoolSize(100);
		executor.initialize();
	} 
	
	@Autowired
	private GISAnalyserExportTask dayAnalyserExport;

	@Autowired
	private GISAnalyserExportTask hourAnalyserExport;

	@RequestMapping("hour/export")
	public void hourExport(
			@RequestParam(value = "datatime", required = false) @DateTimeFormat(pattern = "yyyyMMddHHmmss") Date datatime) {
		if (datatime == null) {
			datatime = new Date();
		}
		hourAnalyserExport.execute(datatime);
	}

	@RequestMapping("day/export")
	public void dayExport(
			@RequestParam(value = "datatime", required = false) @DateTimeFormat(pattern = "yyyyMMdd") Date datatime) {
		if (datatime == null) {
			datatime = new Date();
		}
		dayAnalyserExport.execute(datatime);
	}

	@RequestMapping("hour/batch-export")
	public void hourBatchExport(
			final @RequestParam(value = "starttime") @DateTimeFormat(pattern = "yyyyMMddHHmmss") Date starttime,
			final @RequestParam(value = "endtime") @DateTimeFormat(pattern = "yyyyMMddHHmmss") Date endtime) {
		logger.info("批量导出小时数据");
		executor.execute(new Runnable() {
			@Override
			public void run() {
				Date datatime;
				datatime = starttime;
				while (datatime.before(endtime)) {
					hourAnalyserExport.execute(datatime);
					datatime = DateUtils.addHours(datatime, 1);
				}
			}
		});
	}

	@RequestMapping("day/batch-export")
	public void dayBatchExport(
			final @RequestParam(value = "starttime") @DateTimeFormat(pattern = "yyyyMMdd") Date starttime,
			final @RequestParam(value = "starttime") @DateTimeFormat(pattern = "yyyyMMdd") Date endtime) {
		executor.execute(new Runnable() {
			@Override
			public void run() {
				Date datatime;
				datatime = starttime;
				while (datatime.before(endtime)) {
					dayAnalyserExport.execute(datatime);
					datatime = DateUtils.addDays(datatime, 1);
				}
			}
		});
	}
}
